package com.logicalthinking.socialmall.common.intercepters;

import com.github.chenlijia1111.utils.common.Result;
import com.github.chenlijia1111.utils.http.ResponseUtil;
import com.github.chenlijia1111.utils.oauth.jwt.JWTCheckUtil;
import com.logicalthinking.socialmall.common.pojo.Constants;
import com.logicalthinking.socialmall.entity.Admin;
import com.logicalthinking.socialmall.service.AdminServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.Optional;

/**
 * 后台用户登录拦截器
 *
 * @author Chen LiJia
 * @since 2020/2/18
 */
@Component
public class AdminLoginInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private AdminServiceI adminService;//用户
    @Autowired
    @Qualifier("adminJWTCheckUtil")
    private JWTCheckUtil adminJWTCheckUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Optional<Admin> optional = adminService.currentAdmin();
        if (!optional.isPresent()) {
            ResponseUtil.printRest(Result.notLogin(), response);
            return false;
        }

        //校验成功
        //判断是否需要续期
        Result result = adminJWTCheckUtil.checkToken(request.getHeader(Constants.TOKEN), Constants.JWT_SIGN_KEY);
        if (result.getSuccess() && Objects.nonNull(result.getData())) {
            String newToken = (String) result.getData();
            response.setHeader(Constants.TOKEN, newToken);
        }
        return true;
    }
}
